//
//  ZYFDataConversionTool.m
//  VPOS3695Demo
//
//  Created by 张玉风 on 2018/7/9.
//  Copyright © 2018年 张玉风. All rights reserved.
//

#import "ZYFDataConversionTool.h"

@implementation ZYFDataConversionTool

// 字典转json字符串方法
+(NSString *)convertToJsonData:(NSDictionary *)dict
{
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
//        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    return jsonString;
}

//json转字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
//    NSLog(@"--------------------\n %@",jsonString);
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSRange range = [jsonString rangeOfString:@"}"];
    if (range.location == 0 || range.location == NSNotFound) {
        return nil;
    }
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    jsonString = [jsonString substringWithRange:NSMakeRange(0, range.location)];
    jsonString = [NSString stringWithFormat:@"%@}",jsonString];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments
                                                          error:&err];
    
    if(err)
    {
//        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    //    NSDictionary *dic = [jsonData objectFromJSONData];
    return dic;
}


// 16进制转NSData
+ (NSData *)convertHexStrToData:(NSString *)str
{
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:20];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    return hexData;
}

//普通字符串转换为十六进制的。
+ (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}

+(NSData *)hexString:(NSString *)hexString{
    int j=0;
    Byte bytes[20];
    ///3ds key的Byte 数组， 128位
    for(int i=0; i<[hexString length]; i++)
    {
        int int_ch;  /// 两位16进制数转化后的10进制数
        
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            int_ch1 = (hex_char1-87)*16; //// a 的Ascll - 97
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            int_ch2 = hex_char2-87; //// a 的Ascll - 97
        
        int_ch = int_ch1+int_ch2;
//        NSLog(@"int_ch=%d",int_ch);
        bytes[j] = int_ch;  ///将转化后的数放入Byte数组里
        j++;
    }
    
    NSData *newData = [[NSData alloc] initWithBytes:bytes length:20];
    
    return newData;
    
}

// NSData转16进制 第一种
+ (NSString *)convertDataToHexStr:(NSData *)data
{
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return string;
}

//16进制字符串转成普通字符串
+ (NSString *)stringFromHexString:(NSString *)hexString{
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    
    bzero(myBuffer, [hexString length] / 2 + 1);
    
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        
        unsigned int anInt;
        
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        
        myBuffer[i / 2] = (char)anInt;
        
    }
    
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    
//    NSLog(@"------字符串=======%@",unicodeString);
    
    return unicodeString;
}

///10进制转16进制+5 字符串 不满8位前面填充0
+ (NSString *)getHexByDecimalAdd5:(NSInteger)decimal{
    decimal += 5;
    NSString *hex =@"";
    NSString *letter;
    NSInteger number;
    for (int i = 0; i<9; i++) {
        
        number = decimal % 16;
        decimal = decimal / 16;
        switch (number) {
                
            case 10:
                letter =@"A"; break;
            case 11:
                letter =@"B"; break;
            case 12:
                letter =@"C"; break;
            case 13:
                letter =@"D"; break;
            case 14:
                letter =@"E"; break;
            case 15:
                letter =@"F"; break;
            default:
                letter = [NSString stringWithFormat:@"%ld", (long)number];
        }
        hex = [letter stringByAppendingString:hex];
        if (decimal == 0) {
            
            break;
        }
    }
    NSString *temp = hex;
    for (int i = 0; i < 8 - hex.length; i++) {
        temp = [NSString stringWithFormat:@"0%@",temp];
    }
    return temp;
}

///10进制转16进制字符串 不满8位前面填充0
+ (NSString *)getHexByDecimal:(NSInteger)decimal{
    NSString *hex =@"";
    NSString *letter;
    NSInteger number;
    for (int i = 0; i<9; i++) {
        
        number = decimal % 16;
        decimal = decimal / 16;
        switch (number) {
                
            case 10:
                letter =@"A"; break;
            case 11:
                letter =@"B"; break;
            case 12:
                letter =@"C"; break;
            case 13:
                letter =@"D"; break;
            case 14:
                letter =@"E"; break;
            case 15:
                letter =@"F"; break;
            default:
                letter = [NSString stringWithFormat:@"%ld", (long)number];
        }
        hex = [letter stringByAppendingString:hex];
        if (decimal == 0) {
            
            break;
        }
    }
    NSString *temp = hex;
    for (int i = 0; i < 8 - hex.length; i++) {
        temp = [NSString stringWithFormat:@"0%@",temp];
    }
    return temp;
}

///将传入的字典转换为固定格式的16进制字符串
+(NSString*)hexadecimalToDictionary:(NSDictionary *)dict{
    //将字典转json字符串
    //将json字符串转16进制
    //拼接为固定格式
    NSString * jsonStr = [self convertToJsonData:dict];
    NSString *headStringA = [self getHexByDecimalAdd5:jsonStr.length];
    NSString *headStringB = [self getHexByDecimal:jsonStr.length];
    //
    //    NSLog(@"jsonStr ==== %@  \n %zd \n %@ \n %@ \n ",jsonStr,jsonStr.length,headStringA,headStringB);
    //
    NSString *str16 = [ZYFDataConversionTool hexStringFromString:jsonStr];
    
    NSString *convertStr = [NSString stringWithFormat:@"1000%@11%@%@1001",headStringA,headStringB,str16];
    return [self toUpper:convertStr];
}

///将字符串英文转为大写
+(NSString *)toUpper:(NSString *)str{
    for (NSInteger i=0; i<str.length; i++) {
        if ([str characterAtIndex:i]>='a'&[str characterAtIndex:i]<='z') {
            //A  65  a  97
            char  temp=[str characterAtIndex:i]-32;
            NSRange range=NSMakeRange(i, 1);
            str=[str stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"%c",temp]];
        }
    }
    return str;
}

///将传入的十六进制转换为字典字符串
+(NSString*)dicStringTohexadecimal:(NSString *)str{
    NSString *stringA = [str substringFromIndex:22];
    NSString *stringB = [stringA substringToIndex:stringA.length - 4];
    NSData * data = [self convertHexStrToData:stringB];
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return string;
}

+ (NSDictionary *)dataByDict:(NSData *)data {
    if (!data || data.length < 12) {
        return @{};
    }
    
    NSData *oneData = [data subdataWithRange:NSMakeRange(11, data.length - 11)];
    NSData *lastData = [oneData subdataWithRange:NSMakeRange(0, oneData.length - 2)];
    
//    NSDictionary *dict = [lastData objectFromJSONData];
//    NSDictionary *dict = [ZYFDataConversionTool dataByDict:lastData];
//    NSString *dataStr = [ZYFDataConversionTool convertDataToHexStr:lastData];
    
    //    NSString *dataStr =[[ NSString alloc] initWithData:lastData encoding:NSUTF8StringEncoding];;
    //    dataStr = [dataStr substringFromIndex:22];
    //    dataStr = [dataStr substringWithRange:NSMakeRange(0, dataStr.length - 4)];
//    dataStr =  [ZYFDataConversionTool stringFromHexString:dataStr];
    
//    NSDictionary *dictX = [ZYFDataConversionTool dictionaryWithJsonString:dataStr];
        NSError *err;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:lastData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
    
    return dict;
}

+ (NSData *)strForData:(NSString *)str {
    
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:20];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    
    
    return hexData;
}

+ (NSString *)getFiftyFiveZoon:(NSString *)dataStr {
    
    NSRange headerRange = [dataStr rangeOfString:@"9F33"];
    NSRange footerRange = [dataStr rangeOfString:@"4F08"];
    
    if (headerRange.location != NSNotFound && footerRange.location != NSNotFound ) {
        
        NSString *fiftyFiveZoon = [dataStr substringWithRange:NSMakeRange(headerRange.location, footerRange.location -1)];
        
        return fiftyFiveZoon;
    }
    return @"";
}

+ (NSString *)offlineDealMessage:(NSString *)dataStr {
    
    NSRange headerRange = [dataStr rangeOfString:@"9F78"];
    NSRange footerRange = [dataStr rangeOfString:@"4F"];
    
    if (headerRange.location != NSNotFound && footerRange.location != NSNotFound ) {
        
        NSString *offlineDealMessage = [dataStr substringWithRange:NSMakeRange(headerRange.location, footerRange.location -1)];
        
        return offlineDealMessage;
    }
    return @"";
}

+ (NSString *)getAid:(NSString *)dataStr {
    
    NSRange headerRange = [dataStr rangeOfString:@"4F08"];
    
    if (headerRange.location != NSNotFound ) {
        
        NSString *aid = [dataStr substringWithRange:NSMakeRange(headerRange.location + headerRange.length, 16)];
        
        return aid;
    }
    return @"";
}

@end
